<template>
	<view>
		<!-- #ifdef APP-PLUS -->
		<!-- <view-navbar></view-navbar> -->
		<!-- #endif -->
		<view class="margin">
			<u-gap></u-gap>
			<!--  -->
			<view class="flexflex flex-align justif-between  relative ms20 " ref='top'>
				<u-tabs @click="click" u-sticky :list="list1" lineColor="#7976E9"  itemStyle="padding-left: 60rpx; padding-right: 60rpx;height:88rpx;" :current='currentTab'></u-tabs>
				<view class="" @click="onLongPressCate($event, 1)">
					<u-icon name="plus-circle" size="62rpx" color="#7976e9"></u-icon>
				</view>
			</view>
			<!-- 群 人 -->
			<swiper :current="currentTab" @change="swiperChange" @transition="transition"
				@animationfinish="animationfinish" :style="{height: boxHeight}">
				
				<swiper-item class="swiper-item">
					<scroll-view scroll-y :style="{height: boxHeight}" @scrolltolower="onreachBottom">
						<view>
							<view class="list" v-if="messageSession.length != 0">
								<view class="flex_col" @longpress="onLongPress($event, item)"
									:class="{ active: pickerUserIndex == index }"
									v-for="(item, index) in messageSession" :key="index" :data-index="index"
									@click="listTap(item)">
									<div class="icon">
										<u-avatar :src="item.avatar"></u-avatar>
										<div class="hot" style="" v-if="item.unreadCount!=0">
											<div class="num">{{ item.unreadCount }}</div>
										</div>
										<div v-if="false" class="onLine" style=""></div>
									</div>
									<view class="flex_grow pl-16">
										<view class="flex_col pb-4">
											<view class="flex_grow name textover">{{ item.sessageName || '默认名称' }}</view>
											<view class="time " style="width: 200rpx;" >{{$u.timeFormat(item.createTime, 'yyyy年mm月dd日')}}</view>
										</view>
										<view class="info">
											{{ item.lastMessage }}
										</view>
									</view>
								</view>
							</view>
						</view>
					</scroll-view>
				</swiper-item>
				
				
				<!--  -->
				<swiper-item class="swiper-item">
					<scroll-view scroll-y :style="{height: boxHeight}" @scrolltolower="onreachBottom">
						<view>
							<!-- list -->
							<view class="margin">
								<view class="" v-if="messageList.length">
									<block v-for="item,index in messageList " :key="index">
										<view class="item" :key='index' style="height: 130rpx;" @click="goChat(item)">
											<u-row gutter="10">
												<u-col span="3">
													<view class="flex_col-left">
														<image v-if="item.status == 1" class="slot-image-badge"
															src="/static/img/message/badge.svg"
															style="height: 28px; width: 30px; z-index: 20; "
															mode="heightFix">
														</image>
														<u-avatar :src="item.avatar"></u-avatar>
													</view>

												</u-col>
												<u-col span="8">
													<view class="flex-column text-left">
														<view class="size_18 text-bold  ">
															{{item.unickname || '默认昵称'}}
														</view>
														<view>
															<view v-if="item.status == 1">
																<text style="color: green;">
																	在线
																</text>
															</view>
															<view v-if="item.status == 0">
																<text style="color: red;">
																	离线
																</text>
															</view>
														</view>
													</view>
												</u-col>
											</u-row>
										</view>
									</block>
								</view>
							</view>
						</view>
					</scroll-view>
				</swiper-item>

				<swiper-item class="swiper-item">
					<scroll-view scroll-y :style="{height: boxHeight}" @scrolltolower="onreachBottom">
						<group :messageList="groupLists.list || []" />
					</scroll-view>
				</swiper-item>
			</swiper>

			<!-- 弹框 -->
			<u-popup mode="bottom" :show="show" @close="close" @open="open" :closeable="true">
				<view class="slot margin ">
					<u-gap></u-gap>
					<u-gap></u-gap>
					<u-gap></u-gap>

					<!--  -->
					<u-cell-group>
						<u-cell size="large" title="单元格" value="" v-for="(item, index) in friendList" :key="index">
							<view slot="title" class="u-slot-title flex-align">
								<view class="mr26">
									<u-avatar :src="item.avatar"></u-avatar>
								</view>
								<view class="text-bold size_16">
									{{ item.unickname }}
								</view>
							</view>
							<view class="" slot="value">
								<image v-if="!item.status" @click="addFriendIds(item.userid, item.status, index)"
									src="/static/img/message/msgnb.svg" mode="" style="width: 48rpx;height: 48rpx;">
								</image>
								<image v-else @click="addFriendIds(item.userid, item.status, index)"
									src="/static/img/message/54908.svg" mode="" style="width: 48rpx;height: 48rpx;">
								</image>
							</view>
						</u-cell>
					</u-cell-group>
					<!--  -->
					<view class="ms50 mt40">
						<button @click="bulidCircle" v-if="friendIds.length == 0" class="laBtn1 ">
							<view class="word99">发起圈聊</view>
						</button>
						<button @click="bulidCircle" v-else class="laBtn2 ">
							<view class="word88">发起圈聊</view>
						</button>
					</view>
					<!--  -->
				</view>
			</u-popup>

			<!-- 气泡 -->
			<view class="shade" v-show="showShade" @tap="hidePop">
				<view class="pop" :style="popStyle" :class="{ show: showPop }">
					<view v-for="(item, index) in popButton" :key="index" @tap="pickerMenu" :data-index="index">
						{{ item }}
					</view>
				</view>
			</view>


			<!--  -->
			<view class="shade" v-show="showShadeCate" @tap="hidePopCate">
				<view class="pop" :style="popStyleCate" :class="{ show: showPopCate }">
					<view v-for="(item, index) in popButtonCate" :key="index" @tap="pickerMenuCate(index)"
						:data-index="index">
						{{ item }}
					</view>
				</view>
			</view>


		</view>
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations,
	} from 'vuex'

	import {
		getTimeStringAutoShort,
		fileName,
		uploadFile
	} from "@/utils/myFun.js";
import data from '../../utils/data';
	export default {
		data() {
			return {
				// friend
				messageList: [],
				options1: [{
					text: '删除',
					style: {
						backgroundColor: '#f56c6c'
					}
				}],
				/* 弹框 */
				show: false,
				keyword: '',
				// talkList: [],
				/* 拉群沟通 */
				friendList: [],

				src: ',',
				friendIds: [],
				/* 二维码 */
				addShow: false,
				groupLists: [],
				/* 高 */
				boxHeight: '80vh',
				friednList: [],
				/* tabs */
				currentTab: 0,
				swiperCurrent: 0,
				list1: [{
					name: '会话列表',
					id: 0
				}, {
					name: '密友',
					id: 1
				}, {
					name: '群',
					id: 2
				}],

				/*  */
				pickerUserIndex: -1,
				pickerUserIndexCate: -1,


				/* 弹窗按钮列表 */
				popButton: ["置顶", "取消置顶", "删除记录"],
				// userList: [],
				/* 显示遮罩 */
				showShade: false,
				/* 弹窗定位样式 */
				popStyle: "",
				/* 选择的用户下标 */
				pickerUserIndex: -1,
				/* 显示操作弹窗 */
				showPop: false,
				/* 按钮组需要参数 */
				queryData: null,

				/* 弹框按钮CATE */
				popButtonCate: ["扫一扫", "拉群沟通", "添加好友"],
				// userList: [],
				/* 显示遮罩 */
				showShadeCate: false,
				/* 弹窗定位样式 */
				popStyleCate: "",
				/* 选择的用户下标 */
				pickerUserIndexCate: -1,
				/* 显示操作弹窗 */
				showPopCate: false,
				/* 按钮组需要参数 */
				queryDataCate: null,

			}
		},
		computed: {
			...mapState('m_message', ['talkList', 'messageSession']),
		},
		methods: {
			...mapMutations('m_message', ['TOP_CONVERSATION', 'DELETE_MESSAGE_LIST', 'CANCEL_TOP_CONVERSATION']),
			/*  */
			async listTap(data) {
				/* 因弹出遮罩问题，所以需要在遮罩弹出的情况下阻止列表事件的触发 */
				if (this.showShade) {
					return;
				}
				/* 医生用户id */
				let userId = data.friendId
				let re =  await this.$API.doctorApi.isUemployee(userId)
				/* 是否是医生 */
				let isUemployee = re
				this.toChatroom(data,isUemployee);
			},
			//前往聊天页面
			toChatroom(data,isUemployee) {
				console.log(data, "datadd isUemployee")
				/* 判断是单人 还是 医生 还是 群 */
				// switch (type){
				// 	case value:
				// 		break;
				// 	default:
				// 		break;
				// }
				//todo 会话时间处理
				//todo会话未读数量处理
				if (data.groupId) {
					this.$pub.go(`/pages_message/chatGroup/chatGroup?data=${encodeURIComponent(JSON.stringify(data))}`);
				}else{
					this.$pub.go(`/pages_message/chat/chat?data=${encodeURIComponent(JSON.stringify(data))}`);
				}
				
				// else if (data.friendId && isUemployee == false) {
				// 	this.$pub.go(`/pages_message/chat/chat?data=${encodeURIComponent(JSON.stringify(data))}`);
				// }else if(data.friendId && isUemployee == true){
				// 	this.$pub.go(`/pages_message/chathos/chathos?data=${encodeURIComponent(JSON.stringify(data))}`);
				// }
				
			},



			/* 好友列表 */
			async chatList() {
				let re = await this.$API.friendApi.friendList()
				if (re) {
					this.messageList = re.list || []
				}
			},

			//时间处理
			dateChange(val) {
				return getTimeStringAutoShort(val, true);
			},
			/**
			 * 沟通建圈
			 */
			deleteItem(e) {
				let index = e.index
				this.messageList.splice(index, 1)
			},
			/*  */
			async bulidCircle() {
				let data = {
					"userIds": this.friendIds,
					"avatar": 'https://web.zouwangyun.cn/yijiantong/images/%E7%BE%A4%E5%A4%B4%E5%83%8F.svg',
				}
				let re = await this.$API.friendApi.pullGroup(data)

				this.close()

				this.$router.go(0)
			},

			/**
			 * 勾选人
			 * @param {string} id
			 * @param {string} status
			 * @param {string} index
			 */
			addFriendIds(id, status, index) {
				this.friendList = this.friendList.map(i => {
					if (i.userid == id) {
						i.status = !i.status;
						if (i.status === true) {
							console.log('改添加了');
							this.friendIds.push(id);
						} else {
							console.log('改删除了');
							this.friendIds = this.friendIds?.filter((i) => {
								return i != id
							})
							// this.friendIds.splice(index, 1);
						}
					}
					return i;
				});
				//去除重复
				this.friendIds = [...new Set(this.friendIds)];

			},
			/* 1 */
			/* 长按监听 */
			onLongPress(e, payload) {
				let [touches, style, index] = [
					e.touches[0],
					"",
					e.currentTarget.dataset.index,
				];
				/* 因 非H5端不兼容 style 属性绑定 Object ，所以拼接字符 */
				if (touches.clientY > this.winSize.height / 2) {
					style = `bottom:${this.winSize.height - touches.clientY}px;`;
				} else {
					style = `top:${touches.clientY}px;`;
				}
				if (touches.clientX > this.winSize.witdh / 2) {
					style += `right:${this.winSize.witdh - touches.clientX}px`;
				} else {
					style += `left:${touches.clientX}px`;
				}
				/* 传递id */
				this.queryData = payload;

				this.popStyle = style;
				this.pickerUserIndex = Number(index);
				this.showShade = true;
				this.$nextTick(() => {
					setTimeout(() => {
						this.showPop = true;
					}, 10);
				});
			},
			/* 隐藏弹窗 */
			hidePop() {
				this.showPop = false;
				this.pickerUserIndex = -1;
				setTimeout(() => {
					this.showShade = false;
				}, 250);
			},
			/* 获取窗口尺寸 */
			getWindowSize() {
				uni.getSystemInfo({
					success: (res) => {
						this.winSize = {
							witdh: res.windowWidth,
							height: res.windowHeight,
						};
					},
				});
			},
			/* 选择菜单 */
			pickerMenu(e) {
				console.log(e, "e item");
				let index = Number(e.currentTarget.dataset.index);
				switch (index) {
					case 0:
						console.log('置顶')
						this.TOP_CONVERSATION(this.queryData.messageSessionId)
						break;
					case 1:
						console.log('取消置顶')
						this.CANCEL_TOP_CONVERSATION(this.queryData.messageSessionId)
						break;
					case 2:
						/* 删除记录 */
						console.log('删除')
						this.DELETE_MESSAGE_LIST(this.queryData.messageSessionId);
						break;
				}
				/* 
				 因为隐藏弹窗方法中会将当前选择的用户下标还原为-1,
				 如果行的菜单方法存在异步情况，请在隐藏之前将该值保存，或通过参数传入异步函数中
				 */
				this.hidePop();
			},




			/* 2 */
			onLongPressCate(e, payload) {
				let [touches, style, index] = [
					e.touches[0],
					"",
					e.currentTarget.dataset.index,
				];
				/* 因 非H5端不兼容 style 属性绑定 Object ，所以拼接字符 */
				if (touches.clientY > this.winSize.height / 2) {
					style = `bottom:${this.winSize.height - touches.clientY}px;`;
				} else {
					style = `top:${touches.clientY}px;`;
				}
				if (touches.clientX > this.winSize.witdh / 2) {
					style += `right:${this.winSize.witdh - touches.clientX}px`;
				} else {
					style += `left:${touches.clientX}px`;
				}
				/* 传递id */
				this.queryDataCate = payload;

				this.popStyleCate = style;
				this.pickerUserIndexCate = Number(index);
				this.showShadeCate = true;
				this.$nextTick(() => {
					setTimeout(() => {
						this.showPopCate = true;
					}, 10);
				});
			},
			hidePopCate() {
				this.showPopCate = false;
				this.pickerUserIndexCate = -1;
				setTimeout(() => {
					this.showShadeCate = false;
				}, 250);
			},
			pickerMenuCate(index) {
				// console.log(e, "e item");
				// let index = Number(e.currentTarget.dataset.index);
				switch (index) {
					case 0:
						console.log('qrcode')
						this.qrCode()
						break;
					case 1:
						console.log('pull')
						this.pullGroup()
						break;
					case 2:
						console.log('go')
						this.$pub.go('/pages_message/addFriend/addFriend')
						break;
				}
				/* 
				 因为隐藏弹窗方法中会将当前选择的用户下标还原为-1,
				 如果行的菜单方法存在异步情况，请在隐藏之前将该值保存，或通过参数传入异步函数中
				 */
				this.hidePopCate();
			},

			/* 去聊天 */
			goChat(item) {
				let data = {
					"avatar": item.avatar,
					"friendId": item.userid,
					"sessageName": item.unickname,
				}
				this.$pub.go(`/pages_message/chat/chat?data=${encodeURIComponent(JSON.stringify(data))}`)
			},
			qrCode() {
				uni.scanCode({
					success: async function(res) {
						console.log('扫码结果', res)
						console.log('条码类型：' + res.scanType)
						console.log('条码内容：' + res.result)
					},
				})
			},

			pullGroup() {
				this.open()
			},

			//获取好友列表
			async groupList() {
				let re = await this.$API.friendApi.friendList()
				this.friendList = re?.list.map((i) => {
					i.status = false
					return i
				})

				this.groupLists = await this.$API.friendApi.groupList();
				console.log(this.groupLists, "groupLists");
			},

			close() {
				this.show = false;
				this.friendIds = [];
			},

			open() {
				this.show = true;
				this.groupList()
			},
			addShowChange() {
				this.addShow = !this.addShow
			},
			click(item) {
				this.currentTab = item.index;
			},
			/*  */
			swiperChange(e) {
				let index = e.detail.current;
				this.tabschange(index);
			},

			tabschange(id) {
				this.currentTab = id
			},
			transition() {

			},
			animationfinish() {

			},
			onreachBottom() {

			},



			reflesh() {
				uni.startPullDownRefresh();
				/* 好友列表 */
				this.groupList()
				this.chatList()
				this.getWindowSize();
			}
		},
		onShow() {
			console.log('show');
			this.reflesh()
		},
		onTabItemTap(e) { // tab 点击时执行，此处直接接收单击事件
			if (this.tabClick) {
				this.reflesh() //数据处理
			}
			this.tabClick = true
			setTimeout(() => {
				this.tabClick = false // 200ms 内没有第二次点击，就当作单击
			}, 200)
		},

		onHide() {
			console.log("关闭");
		},
		onPullDownRefresh() {
			let that = this;
			this.chatList()
			this.groupList()
			setTimeout(function() {
				uni.stopPullDownRefresh();
			}, 800);
		},
	}
</script>

<style lang="scss" scoped>
	
	/* 
	 
	:activeStyle="{
								color: '#303133',
								fontWeight: 'bold',
								transform: 'scale(1.05)',
							}" :inactiveStyle="{
								color: '#606266',
								transform: 'scale(1)'
							}" 
	 */
	
	
	
	
	/*  */
	.shade {
		position: fixed;
		z-index: 100;
		top: 0;
		right: 0;
		bottom: 0;
		left: 0;
		-webkit-touch-callout: none;

		.pop {
			position: fixed;
			z-index: 101;
			width: 200upx;
			box-sizing: border-box;
			font-size: 28upx;
			text-align: left;
			color: #333;
			background-color: #fff;
			box-shadow: 0 0 5px rgba(0, 0, 0, 0.5);
			line-height: 80upx;
			transition: transform 0.15s ease-in-out 0s;
			user-select: none;
			-webkit-touch-callout: none;
			transform: scale(0, 0);

			&.show {
				transform: scale(1, 1);
			}

			&>view {
				padding: 0 20upx;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
				user-select: none;
				-webkit-touch-callout: none;

				&:active {
					background-color: #f3f3f3;
				}
			}
		}
	}

	//

	/*  */
	/* #ifdef MP */
	::v-deep .u-tabs__wrapper__nav__item__text {
		font-size: 30rpx !important
	}

	/* #endif */


	/* 修改 u-cell mr26 */
	::v-deep .u-cell__left-icon-wrap {
		margin-right: 52rpx !important;
	}

	.tip {
		width: 168rpx;
		// height: 314rpx;
		height: 160rpx;
		background: #4c4c4c;
		border-radius: 10rpx 10rpx 10rpx 10rpx;
		opacity: 1;
		// translate: -70% 5%;
	}

	.slot-image {
		position: absolute;
		left: 10%;
		height: auto;
	}

	.slot-image-badge {
		position: absolute;
		left: 13%;
		height: auto;
	}

	/* 列表 */
	.list {
		background-color: #fff;
		font-size: 28upx;
		color: #333;
		user-select: none;
		touch-callout: none;

		&>view {
			padding: 24upx 30upx;
			position: relative;

			.icon {
				position: relative;

				// width: 7vw;
				// height: 7vw;
				// margin: 0 1vw 2vw 1vw;
				// 数字气泡
				.hot {
					top: -1vw;
					right: -1vw;
					position: absolute;
					width: 30rpx;
					height: 30rpx;
					border-radius: 40rpx;
					background-color: #ee0a24;
					display: flex;
					justify-content: center;
					text-align: center;

					.num {
						padding-right: 8rpx;
						padding-left: 8rpx;
						color: #fff;
						font-family: PingFang SC;
						font-size: 22rpx;
						font-style: normal;
						font-weight: 500;
						line-height: 30rpx;
					}
				}

				.onLine {
					width: 16rpx;
					height: 16rpx;
					position: absolute;
					bottom: 2vw;
					right: 0vw;
					border-radius: 50%;
					background-color: #4af12a;
				}
			}

			&:active,
			&.active {
				background-color: #f3f3f3;
			}

			image {
				height: 88rpx;
				width: 88rpx;
				// border-radius: 4px;
				border-radius: 50%;
			}

			&>view {
				line-height: 40upx;

				.time,
				.info {
					color: #999;
					font-size: 24upx;
				}

				.name {
					color: #323233;
					font-family: PingFang SC;
					font-size: 14px;
					font-style: normal;
					font-weight: 400;
					line-height: 26rpx;
				}

				.time {
					width: 150upx;
					text-align: right;
				}

				.info {
					height: 26rpx;
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;

					color: #999;
					font-family: PingFang SC;
					font-size: 20rpx;
					font-style: normal;
					font-weight: 400;
					line-height: 26rpx;
				}
			}
		}

		&>view:not(:first-child) {
			margin-top: 1px;

			// &::after {
			//   content: "";
			//   display: block;
			//   height: 0;
			//   border-top: #ccc solid 1px;
			//   width: 620upx;
			//   position: absolute;
			//   top: -1px;
			//   right: 0;
			//   transform: scaleY(0.5); /* 1px像素 */
			// }
		}
	}
	::v-deep .u-tabs__wrapper__nav__item__text{
			font-size: 28rpx !important;
	}
</style>